<template>
  <div class="admin-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">管理员账户管理</h1>
        <p class="page-description">创建和管理系统管理员账户</p>
      </div>
      <div class="page-actions">
        <el-button type="primary" size="large" @click="showAddAdminDialog">
          <el-icon><Plus /></el-icon> 添加管理员
        </el-button>
        <el-button size="large" @click="fetchAdmins" :loading="loading">
          <el-icon><RefreshRight /></el-icon> 刷新
        </el-button>
        <el-button type="info" size="large" @click="$router.push('/admin-logs')">
          <el-icon><Notebook /></el-icon> 查看日志
        </el-button>
      </div>
    </div>
    
    <!-- 筛选器卡片 -->
    <div class="row-container">
      <el-card class="filter-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="card-title">管理员筛选</span>
          </div>
        </template>
        <div class="filter-content">
          <div class="filter-item">
            <el-input
              placeholder="搜索管理员名称"
              v-model="searchQuery"
              clearable
              class="filter-input"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="filter-actions">
            <el-button @click="resetFilters" size="default">
              <el-icon><Refresh /></el-icon> 重置
            </el-button>
            <el-button type="primary" @click="fetchAdmins" size="default">
              <el-icon><Search /></el-icon> 查询
            </el-button>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 管理员表格区域 -->
    <div class="row-container">
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <div class="card-title">管理员列表</div>
          </div>
        </template>
        
        <el-table
          :data="filteredAdmins"
          style="width: 100%"
          v-loading="loading"
          :header-cell-style="{backgroundColor: '#f5f7fa', color: '#303133', fontWeight: '600'}"
        >
          <el-table-column prop="admin_id" label="ID" width="80"></el-table-column>
          <el-table-column prop="admin_name" label="管理员名称"></el-table-column>
          <el-table-column label="管理员级别" width="120">
            <template #default="scope">
              <el-tag :type="getAdminLevelType(scope.row.admin_level)" effect="dark">
                {{ scope.row.admin_level === 0 ? 'boss' : getAdminLevelName(scope.row.admin_level) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="create_at" label="创建时间"></el-table-column>
          <el-table-column label="上次登录时间">
            <template #default="scope">
              {{ scope.row.last_login || '未登录' }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="changeAdminStatus(scope.row)"
                :disabled="scope.row.admin_id === currentAdminId"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <div class="action-buttons">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="editAdmin(scope.row)"
                  :disabled="scope.row.admin_id === currentAdminId">
                  <el-icon><Edit /></el-icon> 编辑
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="deleteAdmin(scope.row)"
                  :disabled="scope.row.admin_id === currentAdminId">
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination">
          <el-pagination
            v-if="totalAdmins > 0"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalAdmins">
          </el-pagination>
        </div>
      </el-card>
    </div>
    
    <!-- 添加/编辑管理员对话框 -->
    <el-dialog :title="isEdit ? '编辑管理员' : '添加管理员'" v-model="dialogVisible" width="40%">
      <el-form :model="adminForm" :rules="adminRules" ref="adminFormRef" label-width="100px">
        <el-form-item label="管理员名称" prop="admin_name">
          <el-input v-model="adminForm.admin_name" placeholder="请输入管理员名称"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="adminForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" v-if="false">
          <el-input v-model="adminForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="管理员级别" prop="admin_level">
          <el-select v-model="adminForm.admin_level" placeholder="请选择管理员级别">
            <el-option :value="1" label="超级管理员"></el-option>
            <el-option :value="2" label="普通管理员"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch v-model="adminForm.is_active" :active-value="true" :inactive-value="false"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 浮动操作区 -->
    <div class="floating-actions">
      <el-button type="primary" @click="fetchAdmins" :loading="loading" class="refresh-btn">
        <el-icon><RefreshRight /></el-icon>
      </el-button>
    </div>
    
    <!-- 底部安全区域 -->
    <div class="bottom-safe-area"></div>
    
    <!-- 当前管理员密码对话框 -->
    <el-dialog title="请输入您的密码" v-model="currentPasswordDialog" width="30%">
      <el-form :model="currentPasswordForm" :rules="currentPasswordRules" ref="currentPasswordFormRef" label-width="100px">
        <el-form-item label="当前密码" prop="password">
          <el-input v-model="currentPasswordForm.password" type="password" placeholder="请输入您的密码" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="currentPasswordDialog = false">取消</el-button>
          <el-button type="primary" @click="submitWithPassword" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { Plus, RefreshRight, Search, Refresh, Delete, Edit, Notebook } from '@element-plus/icons-vue'

export default {
  name: 'AdminPage',
  components: {
    Plus,
    RefreshRight,
    Search,
    Refresh,
    Delete,
    Edit,
    Notebook
  },
  data() {
    return {
      admins: [],
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      totalAdmins: 0,
      loading: false,
      
      // 添加/编辑管理员相关数据
      dialogVisible: false,
      isEdit: false,
      submitLoading: false,
      adminForm: {
        admin_name: '',
        password: '',
        admin_level: 2,
        is_active: true
      },
      // 当前管理员密码对话框
      currentPasswordDialog: false,
      currentPasswordForm: {
        password: ''
      },
      currentPasswordRules: {
        password: [
          { required: true, message: '请输入当前管理员密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
        ]
      },
      tempFormData: null, // 临时存储表单数据
      adminRules: {
        admin_name: [
          { required: true, message: '请输入管理员名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
        ],
        admin_level: [
          { required: true, message: '请选择管理员级别', trigger: 'change' }
        ]
      },
      currentAdminId: null
    }
  },
  created() {
    this.getCurrentAdminInfo()
    this.fetchAdmins()
  },
  computed: {
    filteredAdmins() {
      if (!this.searchQuery) {
        return this.admins
      }
      
      const query = this.searchQuery.toLowerCase()
      return this.admins.filter(admin => 
        (admin.admin_name && admin.admin_name.toLowerCase().includes(query))
      )
    }
  },
  methods: {
    getCurrentAdminInfo() {
      const adminInfoStr = localStorage.getItem('adminInfo')
      if (adminInfoStr) {
        try {
          const adminInfo = JSON.parse(adminInfoStr)
          this.currentAdminId = adminInfo.admin_id
        } catch (error) {
          console.error('解析管理员信息失败:', error)
        }
      }
    },
    fetchAdmins() {
      this.loading = true
      axios.get(`https://smartsound.top/api/v1/admin/list?page_size=${this.pageSize}&page=${this.currentPage}`)
        .then(response => {
          if (response.data.code === 0) {
            this.admins = response.data.data.admins.map(admin => ({
              ...admin,
              admin_id: admin.admin_id,
              admin_name: admin.admin_name,
              admin_level: admin.admin_level,
              status: admin.is_active ? 1 : 0,
              last_login: admin.last_login || '未登录'
            }))
            this.totalAdmins = response.data.data.total
          } else {
            this.$message.error(response.data.message || '获取管理员列表失败')
          }
        })
        .catch(error => {
          console.error('获取管理员列表出错:', error)
          this.$message.error('获取管理员列表失败，请检查网络连接')
        })
        .finally(() => {
          this.loading = false
        })
    },
    resetFilters() {
      this.searchQuery = ''
      this.fetchAdmins()
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.fetchAdmins()
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchAdmins()
    },
    showAddAdminDialog() {
      this.isEdit = false
      this.adminForm = {
        admin_name: '',
        password: '',
        admin_level: 2,
        is_active: true
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.adminFormRef.clearValidate()
      })
    },
    editAdmin(admin) {
      this.isEdit = true
      this.adminForm = {
        admin_id: admin.admin_id,
        admin_name: admin.admin_name,
        admin_level: admin.admin_level,
        is_active: admin.status === 1
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.adminFormRef.clearValidate()
      })
    },
    submitForm() {
      this.$refs.adminFormRef.validate(valid => {
        if (valid) {
          if (!this.isEdit) {
            // 添加管理员时，先询问当前管理员密码
            this.tempFormData = { ...this.adminForm };
            this.currentPasswordDialog = true;
            return;
          }
          
          // 编辑管理员时，需要当前管理员密码
          this.$prompt('请输入您的密码以确认操作', '安全验证', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputType: 'password',
            inputPattern: /.+/,
            inputErrorMessage: '密码不能为空'
          }).then(({ value }) => {
            this.submitLoading = true;
            
            // 构建请求数据
            const data = {
              target_admin_id: this.adminForm.admin_id,
              new_level: this.adminForm.admin_level,
              current_admin_password: value
            };
            
            // 使用正确的API更新管理员权限
            axios.post('https://smartsound.top/api/v1/admin/changeauthority', data)
              .then(response => {
                if (response.data.code === 0) {
                  this.$message.success(`管理员 ${this.adminForm.admin_name} 的权限已更新`);
                  this.dialogVisible = false;
                  this.fetchAdmins();
                } else {
                  this.$message.error(response.data.message || '更新权限失败');
                }
              })
              .catch(error => {
                console.error('更新管理员权限失败:', error);
                this.$message.error('更新管理员权限失败，请检查网络连接或密码是否正确');
              })
              .finally(() => {
                this.submitLoading = false;
              });
          }).catch(() => {
            this.$message.info('已取消操作');
          });
        }
      });
    },
    
    // 确认当前管理员密码并提交添加请求
    submitWithPassword() {
      this.$refs.currentPasswordFormRef.validate(valid => {
        if (valid) {
          this.submitLoading = true;
          this.currentPasswordDialog = false;
          
          const adminInfo = JSON.parse(localStorage.getItem('adminInfo') || '{}');
          
          // 构造符合后端API要求的数据格式
          const submitData = {
            admin_name: this.tempFormData.admin_name,
            admin_password: this.tempFormData.password,
            admin_level: this.tempFormData.admin_level,
            current_admin_name: adminInfo.admin_name || '',
            current_admin_password: this.currentPasswordForm.password
          };
          
          axios.post('https://smartsound.top/api/v1/admin/register', submitData)
            .then(response => {
              if (response.data.code === 0) {
                this.$message.success('添加管理员成功');
                this.dialogVisible = false;
                this.fetchAdmins();
              } else {
                this.$message.error(response.data.message || '添加管理员失败');
              }
            })
            .catch(error => {
              console.error('添加管理员出错:', error);
              this.$message.error('添加管理员失败，请重试');
            })
            .finally(() => {
              this.submitLoading = false;
              this.currentPasswordForm.password = ''; // 清空密码
            });
        }
      });
    },
    deleteAdmin(admin) {
      this.$confirm(`确认删除管理员"${admin.admin_name}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 获取当前管理员信息
        const adminInfo = JSON.parse(localStorage.getItem('adminInfo') || '{}');
        
        // 使用DELETE请求删除管理员，不在URL中包含ID
        axios.delete(`https://smartsound.top/api/v1/admin/delete`, {
          data: {
            target_admin_name: admin.admin_name,
            current_admin_name: adminInfo.admin_name,
            current_admin_password: adminInfo.admin_password || ''
          }
        })
          .then(response => {
            if (response.data.code === 0) {
              this.$message.success('删除管理员成功')
              this.fetchAdmins()
            } else {
              this.$message.error(response.data.message || '删除管理员失败')
            }
          })
          .catch(error => {
            console.error('删除管理员出错:', error)
            this.$message.error('删除管理员失败，请重试')
          })
      }).catch(() => {})
    },
    changeAdminStatus(admin) {
      const isActive = admin.status === 1
      const statusText = isActive ? '启用' : '禁用'
      
      // 提示用户输入密码以确认操作
      this.$prompt('请输入您的密码以确认操作', '安全验证', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'password',
        inputPlaceholder: '请输入您的管理员密码',
        inputPattern: /.+/,
        inputErrorMessage: '密码不能为空'
      }).then(({ value }) => {
        // 调用正确的API接口
        axios.post('https://smartsound.top/api/v1/admin/toggle_active', { 
          target_admin_id: admin.admin_id,
          is_active: isActive,
          current_admin_password: value
        })
          .then(response => {
            if (response.data.code === 0) {
              this.$message.success(`${statusText}管理员成功`)
            } else {
              // 还原状态
              admin.status = isActive ? 0 : 1
              this.$message.error(response.data.message || `${statusText}管理员失败`)
            }
          })
          .catch(error => {
            // 还原状态
            admin.status = isActive ? 0 : 1
            console.error(`${statusText}管理员出错:`, error)
            this.$message.error(`${statusText}管理员失败，请重试`)
          })
      }).catch(() => {
        // 用户取消操作，还原状态
        admin.status = isActive ? 0 : 1
        this.$message.info('已取消操作')
      })
    },
    getAdminLevelType(level) {
      switch(level) {
        case 0: return 'danger';
        case 1: return 'danger';
        case 2: return 'warning';
        default: return 'warning';
      }
    },
    
    getAdminLevelName(level) {
      switch(level) {
        case 0: return 'boss';
        case 1: return '超级管理员';
        case 2: return '普通管理员';
        default: return '未知级别';
      }
    }
  }
}
</script>

<style scoped>
.admin-container {
  padding: 16px 5px;
  position: relative;
  margin-bottom: 80px;
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #1890ff, #722ed1);
  color: white;
  border-radius: 12px;
  padding: 32px 40px;
  margin-bottom: 35px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  position: relative;
}

.page-header::after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 50%;
  background: rgba(255, 255, 255, 0.1);
  transform: skewX(-20deg);
}

.header-content {
  z-index: 1;
}

.page-title {
  font-size: 28px;
  margin: 0 0 12px 0;
  font-weight: 600;
}

.page-description {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
  line-height: 1.6;
}

.page-actions {
  z-index: 1;
  display: flex;
  gap: 10px;
}

/* 行容器样式 */
.row-container {
  margin-bottom: 30px;
  position: relative;
  z-index: 0;
}

/* 卡片基本样式 */
.el-card {
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.03);
  transform: translate3d(0, 0, 0);
  will-change: transform;
  transition: all 0.3s;
}

.el-card:hover {
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
  z-index: 1;
  border-color: rgba(24, 144, 255, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  margin-right: 12px;
}

/* 筛选器卡片样式 */
.filter-card {
  margin-bottom: 20px;
}

.filter-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  padding: 0 10px 10px;
}

.filter-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
  margin-bottom: 5px;
}

.filter-input {
  width: 240px;
}

.filter-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 表格卡片样式 */
.table-card {
  margin-bottom: 30px;
}

/* 表格样式 */
.el-table {
  margin: 10px 0;
  border-radius: 8px;
  overflow: hidden;
}

/* 分页控件 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 8px;
}

/* 按钮样式 */
.el-button {
  border-radius: 4px;
  transition: all 0.3s;
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 浮动操作区 */
.floating-actions {
  position: fixed;
  right: 24px;
  bottom: 24px;
  display: flex;
  align-items: center;
  z-index: 100;
}

.refresh-btn {
  margin-left: 0;
}

/* 底部安全区域 */
.bottom-safe-area {
  height: 60px;
  width: 100%;
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    padding: 24px;
  }
  
  .page-actions {
    margin-top: 20px;
    flex-wrap: wrap;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .floating-actions {
    right: 16px;
    bottom: 16px;
  }
  
  .filter-content {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-item {
    margin-bottom: 15px;
    width: 100%;
  }
  
  .filter-input {
    width: 100%;
  }
  
  .filter-actions {
    width: 100%;
    justify-content: flex-end;
    margin-top: 10px;
  }
}
</style> 